import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import userApi from '../api/api'; // 假设api.js在同一目录下
import { Link, useNavigate } from 'react-router-dom';

const Register = () => {
    const navigator=useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values) => {
    setLoading(true);
    try {
      await userApi.register(values);
      message.success('注册成功即将跳转登录');
      navigator("/")
      
    } catch (error) {
      message.error('注册失败：' + error.response?.data?.message || '未知错误');
      // 处理注册失败的逻辑
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form
      form={form}
      name="register"
      onFinish={onFinish}
      layout="vertical"
    >
      {/* 用户名 */}
      <Form.Item
        name="user_name"
        label="用户名"
        rules={[{ required: true, message: '请输入用户名!' }]}
      >
        <Input />
      </Form.Item>

      {/* 手机号 */}
      <Form.Item
        name="phone"
        label="手机号"
        rules={[{ required: true, message: '请输入手机号!' }]}
      >
        <Input />
      </Form.Item>

      {/* 密码 */}
      <Form.Item
        name="password"
        label="密码"
        rules={[{ required: true, message: '请输入密码!' }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item>
        <Button
          type="primary"
          htmlType="submit"
          loading={loading}
        >
          注册
        </Button>
                      <Link to={"/"}>已有账户登录</Link>
        
      </Form.Item>
    </Form>
  );
};

export default Register;